sort.queue <- function(ctx, k)
{
	# switch with above if smaller
	repeat {
		a <- trunc(k/2)
		if(a <= 0)
			break
		if(ctx$Q[a,1] <= ctx$Q[k,1])
			break
		ctx$Q[c(k,a),] <- ctx$Q[c(a,k),]
		ctx$Qarray[c(ctx$Q[k,2],ctx$Q[a,2])] <- c(k,a)
		k <- a
	}
	# switch below if smaller; choose smallest
	repeat {
		b <- k*2
		if(k*2 >= nrow(ctx$Q))
			break
		k2 <- which.min(c(ctx$Q[k,1], ctx$Q[b,1], ctx$Q[b+1,1]))
		if(k2 == 1)
			break
		b <- k*2+k2-2
		ctx$Q[c(k,b),] <- ctx$Q[c(b,k),]
		ctx$Qarray[c(ctx$Q[k,2],ctx$Q[b,2])] <- c(k,b)
		k <- b
	}
}

# Q <- matrix(c(10.2,11.2,10.3,12.2,13.3,10.5,11.3,13, 1:8), nrow=8)
# Qarray <- 1:8
# Q[1,1] <- 13
# sort.queue(1)
# Q
